package com.woniu.apipassenger.controller;


import com.woniu.apipassenger.manager.RedisLimiterManager;
import com.woniu.apipassenger.service.VerificationCodeService;
import com.woniu.internalcommon.dto.ResponseResult;
import com.woniu.internalcommon.dto.VerificationCodeDTO;
import jakarta.annotation.Resource;

import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class VerificationCodeController {

    @Autowired
    private VerificationCodeService verificationCodeService;
//    @Autowired
//    private RedisLimiterManager redisLimiterManager;
    @Resource
    private RedissonClient redissonClient;
    @PostMapping("/verification-code")
    public ResponseResult verificationCode(@RequestBody VerificationCodeDTO verificationCodeDTO){
        System.out.println("api-passenger  verificaation");
        String passengerPhone = verificationCodeDTO.getPassengerPhone();
        System.out.println(passengerPhone);
        System.out.println("999999999999");
        return verificationCodeService.generatorCode(passengerPhone);

    }

    @PostMapping("/verification-code-check")
    public ResponseResult checkVerificationCode(@RequestBody VerificationCodeDTO verificationCodeDTO) {
        String passengerPhone = verificationCodeDTO.getPassengerPhone();

        // 1. 检查是否被锁定（1分钟内禁止操作）
        RBucket<Boolean> lockBucket = redissonClient.getBucket("verification:lock:" + passengerPhone);
        if (lockBucket.get() != null && lockBucket.get()) {
            return ResponseResult.fail(5656);
        }

        // 2. 限流：10秒内最多10次请求
        RRateLimiter rateLimiter = redissonClient.getRateLimiter("verification:rate:" + passengerPhone);
        rateLimiter.trySetRate(RateType.OVERALL, 10, 10, RateIntervalUnit.SECONDS);

        // 3. 尝试获取令牌
        boolean canOp = rateLimiter.tryAcquire(1);
        if (!canOp) {
            // 触发锁定：1分钟内禁止操作
            lockBucket.set(true, 1, TimeUnit.MINUTES); // 锁定1分钟
            return ResponseResult.fail(5656);
        }

        // 4. 正常处理验证码逻辑
        String verificationCode = verificationCodeDTO.getVerificationCode();
        System.out.println(verificationCodeService.checkCode(passengerPhone, verificationCode));
        return verificationCodeService.checkCode(passengerPhone, verificationCode);
    }

}
